package com.spring.proxy.classloader.gencode;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;  
  
public class JavassistGenerator {  
  
    public static void main(String[] args) throws Exception {  
    	run();  
    }
    public static void run() throws IOException {
		// 读取本地的class文件内的字节码，转换成字节码数组
		InputStream input = new FileInputStream("D:\\temp\\com\\samples\\Programmer.class");
		byte[] result = new byte[1024];

		int count = input.read(result);
		// 使用自定义的类加载器将 byte字节码数组转换为对应的class对象
		MyClassLoader loader = new MyClassLoader();
		Class clazz = loader.defineMyClass(result, 0, count);
		// 测试加载是否成功，打印class 对象的名称
		System.out.println(clazz.getCanonicalName());

		// 实例化一个Programmer对象

		try {
			Object o = clazz.newInstance();
			// 调用Programmer的code方法
			clazz.getMethod("code", null).invoke(o, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static void generateCode() throws CannotCompileException, IOException {
		ClassPool pool = ClassPool.getDefault();  
        //创建Programmer类       
        CtClass cc= pool.makeClass("com.samples.Programmer");  
        //定义code方法  
        CtMethod method = CtNewMethod.make("public void code(){}", cc);  
        //插入方法代码  
        method.insertBefore("System.out.println(\"I'm a Programmer,Just Coding.....\");");  
        cc.addMethod(method);  
        //保存生成的字节码  
        cc.writeFile("d://temp");
	}  
} 